/*
 * Ext JS Library 2.2.1
 * Copyright(c) 2006-2009, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */

FeedGrid = function(viewer, config) {
    this.viewer = viewer;
    Ext.apply(this, config);

    this.store = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: '/gui/command.cgi',
            method:'POST'
           
        }),

        reader: new Ext.data.XmlReader(
            {record: 'item'},
            ['title', 'author', {name:'pubDate', type:'date'}, 'link', 'description', 'content']
        )
    });
    this.store.setDefaultSort('pubDate', "DESC");
    //new code
    this.preview = new Ext.Panel({
        id: 'preview',
        region: 'south',
        cls: 'preview',
        autoScroll: true,
        //listeners: FeedGrid.LinkInterceptor,

        tbar: [{
            id: 'tab',
            text: 'View in New Tab',
            iconCls: 'new-tab',
            disabled: true,
            handler: this.openTab,
            scope: this
        },
        '-',
        {
            id: 'win',
            text: 'Go to Post',
            iconCls: 'new-win',
            disabled: true,
            scope: this,
            handler: function() {
                window.open(this.gsm.getSelected().data.link);
            }
}],

            clear: function() {
                this.body.update('');
                var items = this.topToolbar.items;
                items.get('tab').disable();
                items.get('win').disable();
            }
        });
        
        //end preview
   
        this.tbar = [
                {
                text: 'Start',
                tooltip: { title: 'Start', text: 'Starts/Resumes selected torrents' },
                iconCls: 'tabs',
                handler: this.startTorrents, //todo func
                scope: this
            },{
                text: 'Stop',
                tooltip: { title: 'Stop', text: 'Stops selected torrents' },
                iconCls: 'tabs',
                handler: this.stopTorrents, //todo func
                scope: this
            },{
                text: 'Remove',
                tooltip: { title: 'Start', text: 'Deletes selected torrents and optionally their associated data' },
                iconCls: 'tabs',
                handler: this.remoteTorrents, //todo func
                scope: this
            },
        '-',


            {
                //todo correct type
                text: 'Reading Pane',
                tooltip: { title: 'Reading Pane', text: 'Toggles the details pane on or off' },
                iconCls: 'preview-bottom',
                //todohandler: this.movePreview.createDelegate(this, []),
                
                },
        '-',
                {
                    //pressed: prefs.showSummary,
                    enableToggle: true,
                    text: 'Summary',
                    tooltip: { title: 'Post Summary', text: 'View a short summary of each item in the list' },
                    iconCls: 'summary',
                    scope: this,
                    toggleHandler: function(btn, pressed) {
                        this.grid.togglePreview(pressed);
                    }
                },

                 '-',

                    new Ext.app.SearchField({
                    id: 'searchfield',
                    width: 320
                }),


                {

                    enableToggle: false,
                    text: 'Advanced Search',
                    tooltip: { title: 'Search', text: 'Perform a more specific search with more options' },
                    iconCls: 'summary',
                    scope: this,
                    handler: function() {
                        var searchpane = Ext.getCmp('search-win');
                        //expand the searchpane if it collapsed
                        searchpane.show();
                        if (searchpane.collapsed) { searchpane.expand(); }
                        Ext.getCmp('strQuery').focus('', 200);

                    }
                },
                //Preferences button - spawns PreferencesWindow.js
{
                enableToggle: false,
                text: 'Preferences',
                iconCls: 'prefsicon', //TODO
                scope: this,
                handler: function() {
                    Ext.getCmp('preferences-win').form.getForm().setValues(prefs.defaultSources);
                    Ext.getCmp('preferences-win').show();
                }

            }
            ];
         

  
        
        
        
        
        
        
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        
    this.columns = [{
        
        header: "Title",
        dataIndex: 'title',
        sortable:true,
        width: 420,
        renderer: this.formatTitle
      },{
        header: "Author",
        dataIndex: 'author',
        width: 100,
        hidden: true,
        sortable:true
      },{
       
        header: "Date",
        dataIndex: 'pubDate',
        width: 150,
        renderer:  this.formatDate,
        sortable:true
    }];

    FeedGrid.superclass.constructor.call(this, {
        region: 'center',
        id: 'rssfeeds-grid',
        loadMask: {msg:'Loading View...'},
        tbar: this.tbar,
        sm: new Ext.grid.RowSelectionModel({
            singleSelect:true
        }),

        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            showPreview:true,
            getRowClass : this.applyRowClass
        }
    });

    this.on('rowcontextmenu', this.onContextClick, this);


 this.gsm = this.getSelectionModel();

//    this.gsm.on('rowselect', function(sm, index, record){
//        Application.getTemplate().overwrite(this.preview.body, record.data);
//        var items = this.preview.topToolbar.items;
//        items.get('tab').enable();
//        items.get('win').enable();
//    }, this, {buffer:250});

//    this.store.on('beforeload', this.preview.clear, this.preview);
//    this.store.on('load', this.gsm.selectFirstRow, this.gsm);

//    this.on('rowdblclick', this.openTab, this);

};


Ext.extend(FeedGrid, Ext.grid.GridPanel, {

    onContextClick : function(grid, index, e){
        if(!this.menu){ // create context menu on first right click
            this.menu = new Ext.menu.Menu({
                id:'release-grid-ctx',
                items: [{
                    text: 'View in new tab',
                    iconCls: 'new-tab',
                    scope:this,
                    handler: function(){
                        this.viewer.openTab(this.ctxRecord);
                    }
                },{
                    iconCls: 'new-win',
                    text: 'Go to Post',
                    scope:this,
                    handler: function(){
                        window.open(this.ctxRecord.data.link);
                    }
                },'-',{
                    iconCls: 'refresh-icon',
                    text:'Refresh',
                    scope:this,
                    handler: function(){
                        this.ctxRow = null;
                        this.store.reload();
                    }
                }]
            });
            this.menu.on('hide', this.onContextHide, this);
        }
        e.stopEvent();
        if(this.ctxRow){
            Ext.fly(this.ctxRow).removeClass('x-node-ctx');
            this.ctxRow = null;
        }
        this.ctxRow = this.view.getRow(index);
        this.ctxRecord = this.store.getAt(index);
        Ext.fly(this.ctxRow).addClass('x-node-ctx');
        this.menu.showAt(e.getXY());
    },

    onContextHide : function(){
        if(this.ctxRow){
            Ext.fly(this.ctxRow).removeClass('x-node-ctx');
            this.ctxRow = null;
        }
    },

    loadFeed : function(somefeed) {
//        this.store.baseParams = {
//            action: 'getFeed',
//            feed: somefeed.url
//        };
        this.store.load({params:{'action':'getFeed','feed':somefeed.url}});
    },

    togglePreview : function(show){
        this.view.showPreview = show;
        this.view.refresh();
    },

    // within this function "this" is actually the GridView
    applyRowClass: function(record, rowIndex, p, ds) {
        if (this.showPreview) {
            var xf = Ext.util.Format;
            p.body = '<p>' + xf.ellipsis(xf.stripTags(record.data.description), 200) + '</p>';
            return 'x-grid3-row-expanded';
        }
        return 'x-grid3-row-collapsed';
    },

    formatDate : function(date) {
        if (!date) {
            return '';
        }
        var now = new Date();
        var d = now.clearTime(true);
        var notime = date.clearTime(true).getTime();
        if (notime == d.getTime()) {
            return 'Today ' + date.dateFormat('g:i a');
        }
        d = d.add('d', -6);
        if (d.getTime() <= notime) {
            return date.dateFormat('D g:i a');
        }
        return date.dateFormat('n/j g:i a');
    },

    formatTitle: function(value, p, record) {
        return String.format(
                '<div class="topic"><b>{0}</b><span class="author">{1}</span></div>',
                value, record.data.author, record.id, record.data.forumid
                );
    }
});
